﻿using QueuesLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QueuesServer {
    public class TicketGenerator {
        private Dictionary<Subject, int> counters;

        public TicketGenerator(int initialValue = 0) {
            counters = new Dictionary<Subject, int>();
        }

        public QueuesData.Ticket NextTicket(QueuesData.CurrentSubject subject) {
            using (var db = new QueuesData.QueuesDBEntities()) {
                var ticket = new QueuesData.Ticket();
                ticket.SubjectId = subject.Id;
                ticket.WorkSessionId = db.CurrentWorkSessions.First().Id;
                ticket.CreationTime = DateTime.Now;
                ticket.Number = LastTicketNumber(subject) + 1;
                ticket.Text = subject.Mnemonic + ticket.Number.ToString("000");
                db.Tickets.Add(ticket);
                db.SaveChanges();
                return ticket;
            }
        }

        public int LastTicketNumber(QueuesData.CurrentSubject subject) {
            using (var db = new QueuesData.QueuesDBEntities()) {
                int last = 0;
                var ticketsN = from s in db.SessionTickets
                              where s.SubjectId == subject.Id
                              select s.Number;
                if (ticketsN.Count() > 0) {
                    last = ticketsN.Max();
                }
                return last;
            }
        }
    }
}